package com.bac.rentmap.ad.flat.crawler.irrby;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.springframework.beans.factory.annotation.Required;

import com.bac.rentmap.ad.crawler.Context;
import com.bac.rentmap.ad.crawler.stepped.AbstractSteppedAdCrawler;
import com.bac.rentmap.ad.flat.crawler.FlatCrawledAd;
import com.bac.rentmap.ad.flat.crawler.ParsingHelper;
import com.bac.rentmap.ad.flat.crawler.realtby.RealtBySteppedAdCrawler;
import com.bac.rentmap.ad.util.DateHelper;

public class IrrBySteppedAdCrawler extends
        AbstractSteppedAdCrawler<FlatCrawledAd> {
    private static final Logger log = Logger
            .getLogger(RealtBySteppedAdCrawler.class.getName());

    private Pattern pricePattern = Pattern.compile("(\\d+) \\$");
    private ParsingHelper parsingHelper;
    private DateHelper dateHelper;

    private int page;

    public IrrBySteppedAdCrawler(Context context) {
        if (context.getPage() != null) {
            page = context.getPage() + 1;
        } else {
            page = 1;
        }
    }

    @Override
    protected String getItemXPath() {
//        return "//*[@id='advertsListContainer']/tbody/tr[position() > 2]";
        return "//body/div/div/div/div/div/table/tbody/tr[position() > 2]";
    }

    @Override
    protected String getNextUrl() {
        return "http://irr.by/cat/realestate/rent-flats/longtime/data/field:date/sort:desc/page:"
                + page++ + "-20";
    }

    @Override
    protected FlatCrawledAd parseCrawledAd(TagNode tagNode)
            throws XPatherException {
        FlatCrawledAd res = new FlatCrawledAd();
        String sourceUrl = getValue(tagNode, "/td[3]/div/*/@href");
        res.setSourceUrl("http://irr.by/" + sourceUrl);
        String priceString = getValue(tagNode, "/td[2]/text()");
        log.info("Price " + priceString);
        if (priceString != null)
            res.setPrice(parsePrice(priceString));
        else {
            throw new IllegalArgumentException("Can't parse price for "
                    + sourceUrl);
        }
        res.setReadyForTransformation(false);
        String city = getValue(tagNode, "/td[4]/text()");
        if (city != null) {
            if (city.startsWith("Минск")) {
                res.setCity("minsk");
            } else {
                log.warning("First city character:" + (int) city.charAt(0));
                throw new IllegalArgumentException("Unsupported city " + city);
            }
        } else {
            throw new IllegalArgumentException("Can't parse city from "
                    + tagNode);
        }
        String dateString = getValue(tagNode, "/td[5]/text()");
        Date publishingDate;
        if (dateString.contains("сегодня")) {
            publishingDate = dateHelper.getDateForMidnight();
        } else if (dateString.contains("вчера")) {
            publishingDate = dateHelper.getDateForMidnight(-1);
        } else {
            throw new IllegalArgumentException("Can't parse date from "
                    + dateString);
        }
        res.setPublishingDate(publishingDate);
        return res;
    }

    Integer parsePrice(String priceString) {
        return parsingHelper.parsePrice(priceString, pricePattern);
    }

    @Override
    protected HttpURLConnection createConnection(String url)
            throws MalformedURLException, IOException {
        HttpURLConnection res = super.createConnection(url);
        res
                .setRequestProperty(
                        "Cookie",
                        "records_per_page=30; PHPSESSID=8h868e99qk8n7pd5mnmruug020; __utma=239059032.1014978242.1258145887.1258145887.1258145887.1; __utmb=239059032; __utmc=239059032; __utmz=239059032.1258145887.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none); region=2; cc=1");
        return res;
    }

    @Required
    public void setParsingHelper(ParsingHelper parsingHelper) {
        this.parsingHelper = parsingHelper;
    }

    public void setDateHelper(DateHelper dateHelper) {
        this.dateHelper = dateHelper;
    }
}
